<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use GuzzleHttp\Client;
use GuzzleHttp\Promise;

/**
 * 2020-02-08
 * 这是从cj获取数据判断每天接口新数据
 */
class Cj extends Command
{
    protected $signature = 'cj';
    protected $description = 'cj数据源判断每天新进的卡券数量';
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->info('*********************program start***********************');
        //查询总数量
        $base_url='https://link-search.api.cj.com/v2/link-search?website-id=1962820&advertiser-ids=joined&promotion-type=coupon&records-per-page=100&page-number=';
        $total_url='https://link-search.api.cj.com/v2/link-search?website-id=1962820&advertiser-ids=joined&promotion-type=coupon&records-per-page=1&page-number=1';
        $req_param=[
            'headers'=>[
                'Authorization'=>'Bearer 6t55m4z6hza4a0bm28q8wykkhy'
            ]
        ];

        $client=new Client();
        
        $response=$client->request('GET',$total_url,$req_param);
        $res_data=$response->getBody()->read(120000000);
        
        //对xml数据进行转化
        $res_xml_data=simplexml_load_string($res_data);
        $res_total=(int)$res_xml_data->links['total-matched'];

        //发送异步并发请求 获取数据
        $promises=[];
        for ($i=1; $i <= ceil($res_total/100); $i++) { 
            $promises['page'.$i]= $client->requestAsync('GET',$base_url.$i,$req_param);
        }
        $res_total_data = Promise\unwrap($promises);

        //查询出数据库中已经存在的数据id
        $manager = new \MongoDB\Driver\Manager("mongodb://localhost:27017");

        //查库参数
        $filter = [];
        $options = [
            'projection' => [
                'linkid' => 1,
                '_id'=>0
            ]
        ];

        // 查询数据库中数据
        $query = new \MongoDB\Driver\Query($filter, $options);
        $cursor = $manager->executeQuery('local.cj', $query);
        
        $ids=[];
        foreach ($cursor as $key => $value) {
            $value=(array)$value;
            $ids[]=$value['linkid'];
        }
        
        for ($i=1; $i <= ceil($res_total/100); $i++) { 
            $tosave_data=$res_total_data['page'.$i]->getBody()->read(100000000);
            $tosave_xml_data=simplexml_load_string($tosave_data);
            $coupons=$tosave_xml_data->links->link;
            
            //对接口中获取的coupon数据进行
            $to_save_coupons=[];
            foreach ($coupons as $key => $value) {
                $value=(array)$value;
                if(!in_array($value['link-id'],$ids)){
                    $to_save_coupons[]=[
                        'name'=>$value['advertiser-name'],
                        'advertiser'=>$value['advertiser-id'],
                        'linkid'=>$value['link-id'],
                        'linkname'=>$value['link-name'],
                        'promotion_end_date'=>$value['promotion-end-date'],
                        'promotion_start_date'=>$value['promotion-start-date'],
                        'create_time'=>date('Y-m-d')
                    ];
                }
            }
            //将数据保存到mongodb中
            if($to_save_coupons){
                $bulk = new \MongoDB\Driver\BulkWrite;

                foreach ($to_save_coupons as $key => $value) {
                    $bulk->insert($value); 
                }
                $result=$manager->executeBulkWrite('local.cj', $bulk);
                $this->line('save new data');
            }else{
                $this->line('same data is out');
            }

        }

        $this->info('**********************program stop***********************');
    }
}
